var express = require('express');
var router = express.Router();
const connection = require("../util/db")
const ResultJson = require("../util/json")

/* GET home page. */
router.get('/', function(req, res, next) {
    if (req.cookies.loginInfo) {
        res.redirect("/home")//重定向
    } else {
        res.render('login');//转发页面
    }
});
router.get("/home", function (req, res) {
    res.render("home");
})
router.get("/welcome", function (req, res) {
    res.render("welcome");
})

router.post("/login",function (req, res) {
    const {username,password} = req.body;
    const sql = "select * from userinfo where username = ? and password = ?";
    connection.query(sql,[username,password],function (e,r) {
        if(e){
            throw e;
        }
        const result = r;
        if(result.length === 1){
            const user=result[0];
            if(user.status === 1) {
                res.cookie("loginInfo", JSON.stringify(user), {maxAge: 1000 * 60 * 60 * 2 + 1000 * 60 * 60 * 8})//86400000
                res.json(ResultJson.ok());
            } else {
                res.json(ResultJson.error("该用户已被封禁"))
            }
        } else {
            res.json(ResultJson.error("用户名或密码不正确"));
        }
    })
})

router.get("/logout", function (req, res) {
    res.clearCookie("loginInfo");
    res.redirect("/")
})
module.exports = router;
